package org.spamforces.dao.impl;

import com.google.common.primitives.Ints;
import org.jacuzzi.core.Row;
import org.spamforces.dao.SmsDao;
import org.spamforces.model.Sms;

import java.util.*;

/**
 * @author Maxim Shipko (sladethe@gmail.com)
 *         Date: 09.12.14
 */
public class SmsDaoImpl extends ApplicationDaoImpl<Sms> implements SmsDao {
    @Override
    public Sms find(long id) {
        return super.find(id);
    }

    @Override
    public List<Sms> peek(int maxSize) {
        return findBy("SELECT * FROM `Sms` WHERE status = 'QUEUE' LIMIT ?", maxSize);
    }

    @Override
    public boolean isAnythingInQueue(long broadcastId) {
        return !findBy("SELECT * FROM `Sms` WHERE status = 'QUEUE' and broadcastId = ? LIMIT 1", broadcastId).isEmpty();
    }

    @Override
    public void update(Sms sms) {
        sms.setSentTime(findNow());
        super.update(sms);
    }

    @Override
    public Set<String> smsSetDoneOrQueueByTargetBroadcastId(long broadcastId) {
        List<Row> rows = getJacuzzi().findRows(
                "SELECT phone FROM `Sms` WHERE (status = 'QUEUE' OR status = 'DONE') AND broadcastId = ?", broadcastId
        );

        Set<String> smsSet = new HashSet<>(rows.size());
        for (Row row : rows) {
            smsSet.add(Objects.toString(row.get("phone")));
        }

        return Collections.unmodifiableSet(smsSet);
    }

    @Override
    public void insert(List<Sms> smsList) {
        super.insert(smsList);
    }

    @Override
    public Statistics findStatisticsByBroadcastId(long broadcastId) {
        Statistics statistics = new Statistics();

        statistics.setQueueCount(Ints.checkedCast(getJacuzzi().findLong(
                "SELECT COUNT(*) FROM `Sms` WHERE broadcastId = ? AND status = ?", broadcastId, "QUEUE"
        )));

        statistics.setFailedCount(Ints.checkedCast(getJacuzzi().findLong(
                "SELECT COUNT(*) FROM `Sms` WHERE broadcastId = ? AND status = ?", broadcastId, "FAILED"
        )));

        statistics.setDoneCount(Ints.checkedCast(getJacuzzi().findLong(
                "SELECT COUNT(*) FROM `Sms` WHERE broadcastId = ? AND status = ?", broadcastId, "DONE"
        )));

        return statistics;
    }
}
